package com.linewow.xhyy.nihaonew.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.canyinghao.candialog.CanDialog;
import com.canyinghao.candialog.CanDialogInterface;
import com.fourmob.datetimepicker.date.DatePickerDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.linewow.xhyy.hrxb.DemoHelper;
import com.linewow.xhyy.nihaonew.R;
import com.linewow.xhyy.nihaonew.activity.location.LocationCountryActivity;
import com.linewow.xhyy.nihaonew.activity.user.AdviceActivity;
import com.linewow.xhyy.nihaonew.activity.user.ChangePwdActivity;
import com.linewow.xhyy.nihaonew.activity.user.LanguageActivity;
import com.linewow.xhyy.nihaonew.activity.user.NickActivity;
import com.linewow.xhyy.nihaonew.application.NiHaoApp;
import com.linewow.xhyy.nihaonew.base.BaseEntity;
import com.linewow.xhyy.nihaonew.base.BaseFragmentActivity;
import com.linewow.xhyy.nihaonew.db.NiHaoHelper;
import com.linewow.xhyy.nihaonew.entity.NiHaoEntity;
import com.linewow.xhyy.nihaonew.entity.NiHaoGeneral;
import com.linewow.xhyy.nihaonew.entity.user.UserInfoChange;
import com.linewow.xhyy.nihaonew.helper.GlideImageLoader;
import com.linewow.xhyy.nihaonew.model.AppConstants;
import com.linewow.xhyy.nihaonew.model.HttpModel;
import com.linewow.xhyy.nihaonew.net.api.NiHaoOkgo;
import com.linewow.xhyy.nihaonew.util.DataCleanManager;
import com.linewow.xhyy.nihaonew.util.NewsCallback;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.squareup.picasso.Picasso;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by LXR on 2016/9/20.
 */
public class ConfigureActivity extends BaseFragmentActivity implements DatePickerDialog.OnDateSetListener {

    @Bind(R.id.configure_avatar)
    ImageView configureAvatar;
    @Bind(R.id.configure_nick)
    TextView configureNick;
    @Bind(R.id.configure_nick_rela)
    RelativeLayout configureNickRela;
    @Bind(R.id.configure_birthday)
    TextView configureBirthday;
    @Bind(R.id.configure_birthday_rela)
    RelativeLayout configureBirthdayRela;
    @Bind(R.id.configure_gender)
    TextView configureGender;
    @Bind(R.id.configure_gender_rela)
    RelativeLayout configureGenderRela;
    @Bind(R.id.configure_location)
    TextView configureLocation;
    @Bind(R.id.configure_location_rela)
    RelativeLayout configureLocationRela;
    @Bind(R.id.configure_language)
    TextView configureLanguage;
    @Bind(R.id.configure_language_rela)
    RelativeLayout configureLanguageRela;
    @Bind(R.id.configure_change_pwd)
    RelativeLayout configureChangePwd;
    @Bind(R.id.configure_advice)
    RelativeLayout configureAdvice;
    @Bind(R.id.configure_logout)
    RelativeLayout configureLogout;
    @Bind(R.id.toolbar_back_title)
    TextView toolbarBackTitle;
    @Bind(R.id.toolbar_back_left)
    ImageView toolbarBackLeft;
    @Bind(R.id.toolbar_back_right_tv)
    TextView toolbarBackRightTv;
    @Bind(R.id.configure_cache_rela)
    RelativeLayout configureCacheRela;
    @Bind(R.id.configure_shield)
    RelativeLayout configureShield;
    private NiHaoHelper niHaoHelper;
    private String TAG = "ConfigureActivity";
    private Gson gson;
    private Type userInfoChangeType;
    private int request_code = 100;
    private UserInfoChange userInfoChange;

    final Calendar calendar = Calendar.getInstance();
    final DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(ConfigureActivity.this, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), true);

    @Override
    public void initList() {
        super.initList();
    }

    @Override
    public void initView() {
        super.initView();
        setContentView(R.layout.activity_configure);
        ButterKnife.bind(this);
        niHaoHelper = NiHaoHelper.getInstance();


        configureLanguage.setText(getString(R.string.app_language));
        toolbarBackTitle.setText(getString(R.string.title_configure));

    }

    @Override
    public void initData() {
        super.initData();
        initGson();
        requestInfo();
    }

    private void initGson() {
        gson = new Gson();
        userInfoChangeType = new TypeToken<BaseEntity<UserInfoChange>>() {
        }.getType();
    }

    private void requestInfo() {
        OkHttpUtils.get()
                .url(HttpModel.CONFIGURE + NiHaoApp.token)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        BaseEntity<UserInfoChange> baseEntity = gson.fromJson(response, userInfoChangeType);
                        UserInfoChange userInfo = baseEntity.data;
                        updateUserInfo(userInfo);
                    }
                });
    }

    private void updateUserInfo(UserInfoChange userInfo) {

        this.userInfoChange = userInfo;
        Picasso.with(ConfigureActivity.this).load(userInfo.head_img).error(R.mipmap.err_avatar).fit().into(configureAvatar);
        configureNick.setText(userInfo.nickname);
        configureBirthday.setText(userInfo.birthday);
        if (userInfo.gender.equals("0")) {
            configureGender.setText("");
        } else if (userInfo.gender.equals("1")) {
            configureGender.setText("男");
        } else {
            configureGender.setText("女");
        }
        configureLocation.setText(userInfo.location);


    }


    @OnClick({R.id.configure_avatar,
            R.id.configure_nick_rela,
            R.id.configure_birthday_rela,
            R.id.configure_gender_rela,
            R.id.configure_location_rela,
            R.id.configure_language_rela,
            R.id.configure_change_pwd,
            R.id.configure_advice,
            R.id.configure_cache_rela,
            R.id.configure_shield,
            R.id.configure_logout,
            R.id.toolbar_back_left})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.configure_avatar:
                ImagePicker imagePicker = ImagePicker.getInstance();
                imagePicker.setImageLoader(new GlideImageLoader());
                imagePicker.setMultiMode(false);   //多选true
                imagePicker.setShowCamera(true);  //显示拍照按钮
                imagePicker.setCrop(true);
                imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
                imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
                imagePicker.setFocusHeight(600);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
                Intent intent = new Intent(this, ImageGridActivity.class);
                startActivityForResult(intent, 100);
                break;
            case R.id.configure_nick_rela:

                Intent nickIntent = new Intent(ConfigureActivity.this, NickActivity.class);
                if (userInfoChange != null) {
                    Bundle bundle = new Bundle();
                    bundle.putParcelable("info", userInfoChange);
                    nickIntent.putExtras(bundle);
                }
                startActivityForResult(nickIntent, AppConstants.CONFIGURECODE);


                break;
            case R.id.configure_birthday_rela:
                datePickerDialog.setYearRange(1985, 2010);
                datePickerDialog.show(getSupportFragmentManager(), TAG);
                break;
            case R.id.configure_gender_rela:
                new CanDialog.Builder(this)
                        .setTitle(getString(R.string.title_configure))
                        .setSingleChoiceItems(new String[]{getString(R.string.message_male), getString(R.string.message_female),}, 0, new CanDialogInterface.OnClickListener() {
                            @Override
                            public void onClick(CanDialog dialog, int position, CharSequence text, boolean[] checkitems) {

                            }
                        })
                        .setNegativeButton(getString(R.string.widget_cancel), true, null)
                        .setPositiveButton(getString(R.string.widget_sure), true, new CanDialogInterface.OnClickListener() {
                            @Override
                            public void onClick(CanDialog dialog, int checkItem, CharSequence text, boolean[] checkItems) {
                                Log.e(TAG, "选择的item" + checkItem);
                                if (checkItem == 0) {
                                    setProfile("gender", "1");
                                } else {
                                    setProfile("gender", "2");
                                }
                            }
                        })
                        .setTileAnimator()
                        .setCancelable(true)
                        .setCircularRevealAnimator(CanDialog.CircularRevealStatus.TOP_LEFT)
                        .show();


                break;
            case R.id.configure_location_rela:
                Intent locationIntent = new Intent(ConfigureActivity.this, LocationCountryActivity.class);
                if (userInfoChange != null) {
                    Bundle bundle = new Bundle();
                    bundle.putParcelable("info", userInfoChange);
                    locationIntent.putExtras(bundle);
                }
                startActivityForResult(locationIntent, AppConstants.CONFIGURECODE);
                break;
            case R.id.configure_language_rela:
                Log.e(TAG, "语言");
                Intent intent2 = new Intent(ConfigureActivity.this, LanguageActivity.class);
                startActivity(intent2);


                break;
            case R.id.configure_change_pwd:
                Log.e(TAG, "密码");
                Intent changeIntent = new Intent(ConfigureActivity.this, ChangePwdActivity.class);
                startActivityForResult(changeIntent, AppConstants.CONFIGURECODE);
                break;
            case R.id.configure_advice:
                Log.e(TAG, "建议");

                Intent intent3 = new Intent(ConfigureActivity.this, AdviceActivity.class);
                startActivity(intent3);

                break;
            case R.id.configure_logout:
//                niHaoHelper.logOut();
//                Log.e(TAG, "flag" + NiHaoApp.flag + "---" + NiHaoApp.token);
//                ((NiHaoApp)getApplication()).resumeData();
//                EventBus.getDefault().post(new MessageEvent("logout"), "logout");



                new CanDialog.Builder(ConfigureActivity.this)
                        .setTitle(getString(R.string.menu_notice))
                        .setMessage(getString(R.string.intelligent_log_out))
                        .setCircularRevealAnimator(CanDialog.CircularRevealStatus.TOP_LEFT)
                        .setPositiveButton(getString(R.string.widget_sure), true, new CanDialogInterface.OnClickListener() {
                            @Override
                            public void onClick(CanDialog dialog, int checkItem, CharSequence text, boolean[] checkItems) {
                                DemoHelper.getInstance().logoutUpdate();
                            }
                        })
                        .setNegativeButton(getString(R.string.widget_cancel),true,null)
                        .show();
                break;
            case R.id.configure_cache_rela://清除缓存
                String cacheSize = DataCleanManager.cleanAppCache(ConfigureActivity.this);
                Log.e(TAG, "清除了缓存" + cacheSize);
                showCanDialog(getString(R.string.message_clean_cache)+cacheSize);
                break;
            case R.id.configure_shield:
                Intent shieldIntent = new Intent(ConfigureActivity.this, ShieldActivity.class);
                startActivity(shieldIntent);
                break;

            case R.id.toolbar_back_left:
                finish();
                break;
        }
    }

    @Override
    public void onDateSet(DatePickerDialog datePickerDialog, int year, int month, int day) {
        String value = year + "." + month + "." + day;
        Log.e(TAG, "日期" + value);
        setProfile("brithday", value);
    }

    private void setProfile(String field, String value) {
        showLoading();
        NiHaoOkgo.setProfileInfo(field, value)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NiHaoGeneral<String>>() {
                    @Override
                    public void call(NiHaoGeneral<String> stringNiHaoGeneral) {
                        dismissLoading();
                        if (stringNiHaoGeneral.status) {
                            requestInfo();
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Log.e(TAG, "错误信息" + throwable.getMessage());
                        showToast(getString(R.string.message_no_internet));
                    }
                });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == request_code) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                requestUploadInfo(images.get(0).path);
            } else {
                Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
            }
        } else if (resultCode == AppConstants.CONFIGURECODE) {
            requestInfo();
            mineViewChange();
        } else if (resultCode == AppConstants.CONFIGURECOUNTRYCODE) {
            requestInfo();
        } else if (requestCode == AppConstants.CONFIGURECHANGECODE) {
            finish();
        }

    }

    private void requestUploadInfo(final String path) {
        OkHttpUtils.post()
                .url(HttpModel.USERAVATAR + NiHaoApp.token)
                .addFile("head_img", new File(path).getName(), new File(path))
                .build()
                .execute(new NewsCallback<NiHaoEntity>(NiHaoEntity.class) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        showToast(getString(R.string.message_avatar_fail));
                    }

                    @Override
                    public void onResponse(NiHaoEntity response, int id) {
                        Log.e(TAG, "返回" + response);
                        if (response.status) {
                            Picasso.with(ConfigureActivity.this).load(new File(path)).centerCrop().fit().into(configureAvatar);
                            mineViewChange();//更改  mineview
                        }
                    }
                });
    }

    public void mineViewChange() {
        setResult(AppConstants.CONFIGURECODE);
    }

}
